package com.charles.video.common.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.charles.video.common.core.constant.SecurityConstants;
import com.charles.video.common.core.utils.Convert;
import com.charles.video.common.core.utils.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Charles-H
 * 
 * 获取当前线程中的成员相关信息
 */
public class SecurityContextHolder {
    
    /** 获取当前线程 */
    public static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();
    
    /** 设置set方法 */
    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }
    
    /** 设置字符串类型get方法 */
    public static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
    }
    
    /** 设置泛型get方法 */
    public static <T> T get(String key, Class<T> cla) {
        Map<String, Object> map = getLocalMap();
        return StringUtils.cast(map.getOrDefault(key, null));
    }
    
    /** 获取当前信息 */
    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }
    
    /** 设置当前信息 */
    public static void setLocalMap(Map<String, Object> map) {
        THREAD_LOCAL.set(map);
    }
    
    /** 获取成员id */
    public static Integer getMemberId() {
        return Convert.toInt(get(SecurityConstants.MEMBER_ID), 0);
    }
    
    /** 设置成员id */
    public static void setMemberId(Integer memberId) {
        set(SecurityConstants.MEMBER_ID, memberId);
    }
    
    /** 获取成员工号 */
    public static String getMemberNum() {
        return get(SecurityConstants.MEMBER_NUM);
    }
    
    /** 设置成员工号 */
    public static void setMemberNum(String memberNum) {
        set(SecurityConstants.MEMBER_NUM, memberNum);
    }
    
    /** 获取成员权限 */
    public static String getMemberRole() {
        return get(SecurityConstants.MEMBER_ROLE);
    }
    
    /** 设置成员权限 */
    public static void setMemberRole(String role) {
        set(SecurityConstants.MEMBER_ROLE, role);
    }
    
    /** 获取成员标识 */
    public static String getMemberKey() {
        return get(SecurityConstants.MEMBER_KEY);
    }
    
    /** 设置成员标识 */
    public static void setMemberKey(String memberKey) {
        set(SecurityConstants.MEMBER_KEY, memberKey);
    }
    
    /** 移除线程 */
    public static void remove() {
        THREAD_LOCAL.remove();
    }
    
}
